//
//  HeatProjectViewController.m
//  OutesIOS
//
//  Created by norman on 2019/5/25.
//  Copyright © 2019 norman. All rights reserved.
//

#import "HeatProjectViewController.h"
#import "BuildingTableViewCell.h"
#import "EditorTableViewCell.h"
#import "BigMachine_TabViewController.h"
#import "UITapLabel.h"
#import "BuildingViewController.h"
#import "ReportListViewController.h"


@interface HeatProjectViewController ()

@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) UIView *footerView;
@property (nonatomic,strong) UIBarButtonItem *addBtn;
@property (nonatomic,copy) NSString *projectName;
@property (nonatomic,copy) NSString *cityName;

@end

@implementation HeatProjectViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initData];
    self.title = @"基本信息";
    [self setupBaseViews];
    [self setupViews];
    // Do any additional setup after loading the view.
}

#pragma mark - 初始化视图
- (void)setupBaseViews {
    //自定义返回按钮
    UIBarButtonItem *backBtn = [[UIBarButtonItem alloc] initWithTitle:@"项目" style:UIBarButtonItemStyleDone target:self action:@selector(onBackToProject)];
    self.navigationItem.leftBarButtonItem = backBtn;
    
    //添加按钮
    self.addBtn = [[UIBarButtonItem alloc] initWithTitle:@"添加建筑" style:UIBarButtonItemStyleDone target:self action:@selector(addNewBuilding)];
//    self.navigationItem.rightBarButtonItem = self.addBtn;
    
    //底部的上一步，下一步按钮
    self.footerView = [[UIView alloc]initWithFrame:CGRectMake(0, self.view.height - KAction_Bar_Height - kNavigation_Bar_Height - kStatus_Bar_Height, kScreen_Width, KAction_Bar_Height)];
    if (iPhone_X) {
        self.footerView.y -= 34;
    }
    self.footerView.backgroundColor = CM_TABLE_BG_COLOR;
    UITapLabel *preView = [[UITapLabel alloc]initWithFrame:CGRectMake(0, 1, kScreen_Width/4, KAction_Bar_Height - 1)];
    preView.backgroundColor = CM_DARKGREEN_COLOR;
    preView.text = @"预览";
    preView.textAlignment = NSTextAlignmentCenter;
    preView.textColor = [UIColor whiteColor];
    [self.footerView addSubview:preView];
    [preView addTargetsBlock:^(id obj) {
        [Tools showMessageCenter:@"预览"];
    }];
    
    UITapLabel *reportView = [[UITapLabel alloc]initWithFrame:CGRectMake(kScreen_Width/4, 1, kScreen_Width/2, KAction_Bar_Height - 1)];
    reportView.backgroundColor = CM_ORANGE_COLOR;
    reportView.text = @"报告生成";
    reportView.textAlignment = NSTextAlignmentCenter;
    reportView.textColor = [UIColor whiteColor];
    [self.footerView addSubview:reportView];
    [reportView addTargetsBlock:^(id obj) {
        [Tools showMessageCenter:@"报告生成"];
    }];
    
    UITapLabel *listView = [[UITapLabel alloc]initWithFrame:CGRectMake(kScreen_Width*3/4, 1, kScreen_Width/4, KAction_Bar_Height - 1)];
    listView.backgroundColor = CM_DARKGREEN_COLOR;
    listView.text = @"列表";
    listView.textAlignment = NSTextAlignmentCenter;
    listView.textColor = [UIColor whiteColor];
    [self.footerView addSubview:listView];
    [listView addTargetsBlock:^(id obj) {
        ReportListViewController *vc = [ReportListViewController new];
        [self.navigationController pushViewController:vc animated:YES];
    }];
    
    [self.view addSubview:self.footerView];
}


- (void)setupViews{
    //列表
    self.tableView = [[UITableView alloc] initWithFrame:[UIView frameWithOutNavBottom] style:UITableViewStylePlain];
    [self.tableView registerClass:[EditorTableViewCell class] forCellReuseIdentifier:@"edit"];
    [self.tableView registerClass:[BuildingTableViewCell class] forCellReuseIdentifier:@"building"];
    self.tableView.backgroundColor = UIColor16(0xeeeeee);
    [self.tableView setSeparatorColor: UIColor16(0xeeeeee)];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    //去掉多余的分割线
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    [self.view addSubview:self.tableView];
    //下拉刷新
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadData)];
    [self.tableView.mj_header beginRefreshing];
}

/**
 *  直接跳转到项目页面
 */
-(void) onBackToProject{
    //返回到首页
    for (UIViewController *tmp in self.navigationController.viewControllers) {
        if ([tmp isKindOfClass:[BigMachine_TabViewController class]]) {
            [(BigMachine_TabViewController*)tmp loadData];
            [self.navigationController popToViewController:tmp animated:YES];
        }
    }
}

- (void)cityName:(NSString *)name {
    self.cityName = name;
    [[DBManager manager]open:DB_Weather];
    NSString *cityId = [[DBManager manager]queryStringData:[NSString stringWithFormat:@"select Id from Cities WHERE Name = '%@'",name]];
    NSMutableDictionary *city = [NSMutableDictionary new];
    [city setObject:name forKey:@"city"];
    [city setObject:cityId forKey:@"id"];
    [Tools saveApplicationData:city forKey:CityName];
    [self updateProojectNameAndCity];
}

#pragma 数据处理
/**
 *  初始化数据
 */
- (void)initData {
    kHeatProject = nil;
    NSDictionary *city = [Tools getApplicationData:CityName];
    if (city == nil) {
        return;
    }
    self.cityName = [city objectForKey:@"city"];
}

- (void)loadData {
    if (![Tools isEmpty:self.heat_project_id]) {
        //修改项目
        NSMutableDictionary *param = [NSMutableDictionary dictionary];
        [param setValue:self.heat_project_id forKey:@"heat_project_id"];
        
        [HttpClient getWithUrl:HTTP_GET_HEAT_PROJECT_INFO token:[[AccountManager manager]token] paramDic:param resultClass:[HeatProjectData class] success:^(HeatProjectData *obj) {
            //下拉刷新
            [self.tableView.mj_header endRefreshing];
            kHeatProject = obj;
            self.projectName = obj.heat_project_name;
            self.navigationItem.rightBarButtonItem = self.addBtn;
            [self.tableView reloadData];
        } failure:^(NSError *error) {
            [self.tableView.mj_header endRefreshing];
        }];
    } else {
        [self.tableView.mj_header endRefreshing];
    }
}

- (void)updateProojectNameAndCity {
    if ([Tools isEmpty:self.projectName] || [Tools isEmpty:self.cityName]) {
        return;
    }
    if ([Tools isEmpty:self.heat_project_id]) {
        //新建项目
        [self createNewProject];
    } else {
        NSMutableDictionary *param = [NSMutableDictionary dictionary];
        NSDictionary *city = [Tools getApplicationData:CityName];
        NSString *name = [city objectForKey:@"city"];
        NSString *guid = [city objectForKey:@"id"];
        [param setValue:name forKey:@"city_name"];
        [param setValue:guid forKey:@"city_id"];
        [param setValue:self.projectName forKey:@"heat_project_name"];
        [HttpClient postWithUrl:HTTP_POST_HEAT_PROJECT_NAME_CITY_UPDATE token:[[AccountManager manager]token] paramDic:param resultClass:[HeatProjectData class] success:^(HeatProjectData *obj) {
            self.cityName = obj.city_name;
            kHeatProject.city_name = self.cityName;
            kHeatProject.city_id = guid;
            kHeatProject.heat_project_name = self.projectName;
        } failure:^(NSError *error) {
        }];
    }
}

- (void)createNewProject {
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    NSDictionary *city = [Tools getApplicationData:CityName];
    if ([Tools isEmpty:self.projectName] || city == nil) {
        return;
    }
    NSString *name = [city objectForKey:@"city"];
    NSString *guid = [city objectForKey:@"id"];
    if ([Tools isEmpty:name] || [Tools isEmpty:guid]) {
        return;
    }
    [param setValue:name forKey:@"city_name"];
    [param setValue:guid forKey:@"city_id"];
    [param setValue:self.projectName forKey:@"heat_project_name"];
    [HttpClient postWithUrl:HTTP_POST_HEAT_PROJECT_NEW token:[[AccountManager manager]token] paramDic:param resultClass:[HeatProjectData class] success:^(HeatProjectData *obj) {
        //下拉刷新
        [self.tableView.mj_header endRefreshing];
        self.heat_project_id = obj.heat_project_id;
        self.cityName = obj.city_name;
        kHeatProject = obj;
        self.navigationItem.rightBarButtonItem = self.addBtn;
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        [self.tableView.mj_header endRefreshing];
    }];
}

/**
 *  添加新建筑
 */
- (void)addNewBuilding {
    if ([Tools isEmpty:self.heat_project_id]) {
        return;
    }
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setValue:kHeatProject.heat_project_id forKey:@"heat_project_id"];
    [HttpClient getWithUrl:HTTP_GET_HEAT_PROJECT_BUILDING_NEW token:[AccountManager manager].token paramDic:params resultClass:[BuildingData class] success:^(BuildingData *obj) {
        if (kHeatProject.buildings == nil) {
            kHeatProject.buildings = [NSMutableArray new];
        }
        [kHeatProject.buildings addObject:obj];
        [self.tableView reloadData];
    } failure:^(NSError *error) {
    }];
}

- (void)deleteBuilding:(NSInteger) tag {
    BuildingData *date = [kHeatProject.buildings objectAtIndex:tag];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setValue:date.building_id forKey:@"building_id"];
    [HttpClient getWithUrl:HTTP_GET_HEAT_PROJECT_BUILDING_DELETE token:[AccountManager manager].token paramDic:params resultClass:[CommonResponse class] success:^(CommonResponse *obj) {
        [kHeatProject.buildings removeObjectAtIndex:tag];
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        [Tools showMessageCenter:@"删除建筑失败！"];
    }];
}


#pragma mark - tableView显示设置数据
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1 + kHeatProject.buildings.count;;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return 2;
    }
    return 1;
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            EditorTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"edit"];
            [cell setKeyboardType:UIKeyboardTypeDefault];
            if (![Tools isEmpty:self.projectName]) {
                [cell setTitleStr:@"项目名称" andColor:nil andHintStr:@"XX工程XXX项目" andInputViewIsHidden:NO andInfoStr:kHeatProject.heat_project_name andUnit:nil];
                [cell setEditorText:kHeatProject.heat_project_name];
            }
            else {
                [cell setTitleStr:@"项目名称" andColor:nil andHintStr:@"XX工程XXX项目" andInputViewIsHidden:NO andInfoStr:nil andUnit:nil];
            }
            cell.TextFiledValueBlock = ^(NSString *value) {
                self.projectName = value;
            };
            cell.TextFiledEditingEndBlock = ^(NSString *value) {
                [self updateProojectNameAndCity];
            };
            return cell;
        } else {
            UITableViewCell *Selectcell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"SelectArea_Cell"];
            Selectcell.textLabel.textColor = CM_TABLE_TITLE_COLOR;
            Selectcell.detailTextLabel.textColor = CM_TABLE_INFO_COLOR;
            Selectcell.textLabel.text = @"所在城市";
            if ([Tools isEmpty:self.cityName]) {
                Selectcell.detailTextLabel.text = @"请选择";
            } else {
                Selectcell.detailTextLabel.text = kHeatProject.city_name;
            }
            Selectcell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            return Selectcell;
        }
    } else {
        static NSString *identifier = @"ProjectModuleCell";
        BuildingTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (cell == nil) {
            cell = [[BuildingTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        BuildingData *item = [kHeatProject.buildings objectAtIndex:indexPath.row];
        [cell setData:item];
        //滑动按钮
        cell.rightUtilityButtons = [self rightButtons];
        cell.delegate = self;
        cell.tag = indexPath.row;
        return cell;
    }
}

-(NSArray *)rightButtons {
    NSMutableArray *rightUtilityButtons = [NSMutableArray new];
    [rightUtilityButtons sw_addUtilityButtonWithColor:[UIColor redColor] title:@"删除"];
    return rightUtilityButtons;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 0) {
        if (indexPath.row == 1) {
            //选择地点
            JFCityViewController *cityViewController = [[JFCityViewController alloc] init];
            //  设置代理
            cityViewController.delegate = self;
            cityViewController.title = @"城市";
            //  给JFCityViewController添加一个导航控制器
            UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:cityViewController];
            [navigationController.navigationBar setTintColor:[UIColor whiteColor]];
            [self presentViewController:navigationController animated:YES completion:nil];
        }
    } else {
        BuildingViewController *view = [BuildingViewController new];
        view.currentIndex = indexPath.row;
        view.buildingInfoChangedBlock = ^() {
            [self.tableView reloadData];
        };
        [self.navigationController pushViewController:view animated:YES];
    }
    
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        static NSString *identifier = @"edit";
        EditorTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (cell == nil) {
            cell = [[EditorTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier];
            //cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        }
        return [cell getHeight];
    }
    return [BuildingTableViewCell cellHeight];
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreen_Width, CGFLOAT_MIN)];
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return CGFLOAT_MIN;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    if (section == 0) {
        return [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreen_Width, 5)];
    }
    return [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreen_Width, CGFLOAT_MIN)];
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if (section == 0) {
        return 5;
    }
    return CGFLOAT_MIN;
}


#pragma mark - 滑动按钮代理协议
/**
 *  右侧滑动按钮点击事件
 *
 *  @param cell  单元cell
 *  @param index 下标
 */
-(void)swipeableTableViewCell:(SWTableViewCell *)cell didTriggerRightUtilityButtonWithIndex:(NSInteger)index{
    switch (index) {
        case 0:{
            [self deleteBuilding:cell.tag];
            break;
        }
            
        default:
            break;
    }
    [cell hideUtilityButtonsAnimated:YES];
}


/**
 *  滑动的时候把其他的隐藏掉
 *
 *  @param cell cell
 *
 *  @return 隐藏其他的cell
 */
-(BOOL)swipeableTableViewCellShouldHideUtilityButtonsOnSwipe:(SWTableViewCell *)cell{
    return YES;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
